<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'shop:order:soAdvanceOrder:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #soAdvanceOrderChildList>
        <BasicTable
          @register="registerSoAdvanceOrderChildTable"
          @row-click="handleSoAdvanceOrderChildRowClick"
        />
        <a-button class="mt-2" @click="handleSoAdvanceOrderChildAdd" v-auth="'shop:order:soAdvanceOrder:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderSoAdvanceOrderForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { SoAdvanceOrder, soAdvanceOrderSave, soAdvanceOrderForm } from '/@/api/shop/order/soAdvanceOrder';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.soAdvanceOrder');
  const { showMessage } = useMessage();
  const record = ref<SoAdvanceOrder>({} as SoAdvanceOrder);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增销售预订单') : t('编辑销售预订单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('客户编码'),
      field: 'cusCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('存货编码'),
      field: 'invCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('核发门店编码'),
      field: 'hfmdCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('使用促销金额'),
      field: 'cxMoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('使用返利金额'),
      field: 'flMoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('协同路线'),
      field: 'croute',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('数量'),
      field: 'iquantity',
      component: 'Input',
      componentProps: {
        maxlength: 51,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('件数'),
      field: 'inum',
      component: 'Input',
      componentProps: {
        maxlength: 51,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('单价'),
      field: 'salePrice',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('金额'),
      field: 'isum',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('销售预订单'),
      field: 'soAdvanceOrderChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'soAdvanceOrderChildList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerSoAdvanceOrderChildTable, soAdvanceOrderChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleSoAdvanceOrderChildDelete.bind(this, record),
          },
          auth: 'shop:order:soAdvanceOrder:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setSoAdvanceOrderChildTableData(_res: Recordable) {
    soAdvanceOrderChildTable.setColumns([
      {
        title: t('存货编码'),
        dataIndex: 'invCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iquantity',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 51,
        },
        editRule: true,
      },
      {
        title: t('件数'),
        dataIndex: 'inum',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 51,
        },
        editRule: false,
      },
      {
        title: t('单价'),
        dataIndex: 'salePrice',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('金额'),
        dataIndex: 'isum',
        width: 130,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
    ]);
    soAdvanceOrderChildTable.setTableData(record.value.soAdvanceOrderChildList || []);
  }

  function handleSoAdvanceOrderChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleSoAdvanceOrderChildAdd() {
    soAdvanceOrderChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleSoAdvanceOrderChildDelete(record: Recordable) {
    soAdvanceOrderChildTable.deleteTableDataRecord(record);
  }

  async function getSoAdvanceOrderChildList() {
    let soAdvanceOrderChildListValid = true;
    let soAdvanceOrderChildList: Recordable[] = [];
    for (const record of soAdvanceOrderChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        soAdvanceOrderChildListValid = false;
      }
      soAdvanceOrderChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of soAdvanceOrderChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      soAdvanceOrderChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!soAdvanceOrderChildListValid) {
      throw { errorFields: [{ name: ['soAdvanceOrderChildList'] }] };
    }
    return soAdvanceOrderChildList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await soAdvanceOrderForm(data);
    record.value = (res.soAdvanceOrder || {}) as SoAdvanceOrder;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setSoAdvanceOrderChildTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.soAdvanceOrderChildList = await getSoAdvanceOrderChildList();
      // console.log('submit', params, data, record);
      const res = await soAdvanceOrderSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
